package com.shtel.paas.monitorcenter.process.management.service.util.sshtool;

/**
 * @ClassName
 * @Description Too
 * @Author ME
 * @Data zhoujie 17:33
 **/
import java.io.*;
import java.util.Vector;

import javax.naming.spi.DirStateFactory.Result;

import com.jcraft.jsch.*;
import org.springframework.beans.factory.annotation.Value;

/**
 * This class provide interface to execute command on remote Linux.
 */

public class SSHMultiCommandExecutor {

    public String ip;
    public String port;
    public String pid;
    public String user;
    public String status;
    public String cpu_use;
    public String cmd;
    public String start_time;
    public String memory_use;

    public int returnCode=0;

    @Value("${sshPath}")
    private String sshPath;

    private String username="patrol";

    private String password="patrol-1";



    String[] commands={"sudo netstat -tlnp |grep :#PORT#| grep -v grep",
            "ps aux|grep #PID#| grep -v grep "};

    public static final int DEFAULT_SSH_PORT = 22;

    private Vector<String> stdout=new Vector<String>();;

    public SSHMultiCommandExecutor(final String ipAddress, final String port) {
        this.ip = ipAddress;
        this.port = port;
    }

    public SSHMultiCommandExecutor(String ip, String port, String username, String password) {
        super();
        this.ip = ip;
        this.port = port;
        this.username = username;
        this.password = password;
    }

    public SSHMultiCommandExecutor execute() throws JSchException {

        JSch jsch = new JSch();
     //   jsch.addIdentity("/bmc/.ssh/id_rsa");
        jsch.addIdentity(sshPath);
        MyUserInfo userInfo = new MyUserInfo();
        Session session = jsch.getSession(username, ip, DEFAULT_SSH_PORT);
        System.out.println(">>getSession by "+ip+" username"+username+" port:"+port);
        session.setPassword(password);
        session.setUserInfo(userInfo);
        session.connect();

        ChannelShell channel = (ChannelShell) session.openChannel("shell");

        channel.connect();
        try {
            // Create and connect session.



            InputStream inputStream = channel.getInputStream();//从远程端到达的所有数据都能从这个流中读取到
            OutputStream outputStream = channel.getOutputStream();//写入该流的所有数据都将发送到远程端。
            //使用PrintWriter流的目的就是为了使用println这个方法
            //好处就是不需要每次手动给字符串加\n
            PrintWriter printWriter = new PrintWriter(outputStream);


            printWriter.println(commands[0].replace("#PORT#", this.port));
            printWriter.flush();

            new Thread(()->{


                BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
                String msg = null;
                try {
                    while((msg = in.readLine())!=null){
                        //if(msg.contains(":50070")){
                        // System.out.println(msg);
                        if(this.pid==null&&msg.contains(port)&&!msg.contains("grep")){
                            String temp = msg.split("\\s+")[6];
                            //System.out.println("temp "+temp);
                            this.pid=temp.substring(0,temp.indexOf("/") );
                            System.out.println("pid is "+this.pid);
                        }else if(this.pid!=null&&msg.contains(pid)&&!msg.contains("grep")&&!msg.contains("LISTEN")){
                            String[] ps = msg.split("\\s+");
//					    	for(String s:ps){
//					    		System.out.println("[]:"+s);
//					    	}
                            System.out.println("aux:"+msg);
                            user = ps[0];
                            status = ps[7];
                            cpu_use = ps[2];
                            memory_use = ps[3];
                            start_time =ps[8]+" "+ps[9];
                            String tempCmd = "";
                            for(int i=10;i<ps.length;i++){
                                tempCmd=tempCmd.concat(ps[i]+" ");
                            }
                            cmd= tempCmd;

                        }
                        //}
                    }
                    //in.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
            int j=20;
            while(this.pid==null&&j>0){
                Thread.sleep(100L);
                j--;
            }

            if(pid==null){
                channel.disconnect();
                session.disconnect();
                return null;
            }

            printWriter.println(commands[1].replace("#PID#", this.pid));
            printWriter.println("exit");//加上个就是为了，结束本次交互
            printWriter.flush();




            j=20;
            while(this.cpu_use==null&&j>0){
                Thread.sleep(100L);
                j--;
            }
            if(cpu_use==null){
                channel.disconnect();
                session.disconnect();
                return null;
            }
            if (channel.isClosed()) {
                returnCode = channel.getExitStatus();
            }
            // Disconnect the channel and session.

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            channel.disconnect();
            session.disconnect();

        }
        return this;
    }

    public Vector<String> getStandardOutput() {
        return stdout;
    }

    public static void main(final String [] args) throws JSchException {
        //进入机器
        SSHMultiCommandExecutor sshExecutor = new SSHMultiCommandExecutor("10.145.242.13","50070", "spark", "Spar1oon");
        //根据端口取 pid



        SSHMultiCommandExecutor res = sshExecutor.execute();


        System.out.println("res is "+res);


    }

    @Override
    public String toString() {
        return "SSHMultiCommandExecutor [ip=" + ip + ", port=" + port + ", pid=" + pid + ", status=" + status
                + ", cpu_use=" + cpu_use + ", cmd=" + cmd + ", start_time=" + start_time + ", memory_use=" + memory_use
                + ", returnCode=" + returnCode + "]";
    }


}
